<?php

namespace App\Kuafu\CouponExt\Channel;


use App\Kuafu\Config\Model\ConfigModel;
use App\Kuafu\Config\Service\ConfigService;
use App\Kuafu\CouponExt\Channel\DouYin\DouyinCouponBase;
use App\Kuafu\CouponExt\Channel\MeiTuan\MeiTuanBase;
use App\Kuafu\CouponExt\Channel\MeiTuan\MeiTuanBaseMock;
use App\Kuafu\CouponExt\Channel\Xhs\XhsCouponBase;
use App\Kuafu\CouponExt\Enum\CouponExtEnum;
use App\Kuafu\CouponExt\Exceptions\CouponExtException;
use App\Kuafu\Order\Service\OrderCouponExternalService;
use App\Kuafu\Product\Service\ProductShopService;
use Exception;
use App\Library\FeiShu\SendFs;
use Illuminate\Support\Facades\Cache;
use Kuafu\GeneralFs\BuildFs;

class CouponExtBase
{
    private static $ins;


    public function __construct()
    {

    }

    /**
     * @param int $shopId
     * @param int $extType
     * @return DouyinCouponBase|MeiTuanBase|MeiTuanBaseMock|XhsCouponBase
     * @throws CouponExtException
     * @throws Exception
     */
    public static function getIns(int $shopId, int $extType = CouponExtEnum::EXT_PLATFORM_MEITUAN)
    {
        switch ($extType) {
            case CouponExtEnum::EXT_PLATFORM_MEITUAN:
                if (config('app.pressure')) {
                    return new MeiTuanBaseMock($shopId);
                }

                if (self::$ins instanceof MeiTuanBase) {
                    return self::$ins;
                }

                return self::$ins = new MeiTuanBase($shopId);
            case CouponExtEnum::EXT_PLATFORM_DOUYIN:

                if (self::$ins instanceof DouyinCouponBase) {
                    return self::$ins;
                }
                return self::$ins = new DouyinCouponBase(0, $shopId);
            case CouponExtEnum::EXT_PLATFORM_XHS://小红书券码
                if (!self::$ins instanceof XhsCouponBase) {
                    self::$ins = new XhsCouponBase(0, $shopId);
                }
                break;
            default:
                throw new Exception("门店核销券码类型有误 【 $shopId 】【 $extType 】");
        }

        return self::$ins;
    }

    /**
     * 接口返回通用处理
     * @param bool $status
     * @param string $code
     * @param string $msg
     * @param array $oriData
     * @return array
     */
    protected function returnFormatData(bool $status, string $code, string $msg, array $oriData): array
    {
        return [
            'status'  => $status, // true: 接口成功 false: 接口失败
            'code'    => $code, // 错误码
            'msg'     => $msg,  // 错误信息
            'data'    => [],   // 多种支付渠道合并后的，固定通用返回字段
            'oriData' => $oriData, //
        ];
    }

    /**
     * @param int $type
     * @param array $couponPrepareData
     * @param int $shopId
     * @return string
     * @throws Exception
     */
    public static function getCanUseProductBySkuId(int $type, array $couponPrepareData, int $shopId): string
    {
        $skuId = $couponPrepareData['skuId'] ?? '';

        // 代金券 out
        if (in_array($couponPrepareData['couponType'], [
            CouponExtEnum::COUPON_TYPE_MONEY
        ])) {
            return '';
        }

        $robotConfig = self::getRobotByType($type);

        if (!empty($couponPrepareData['canUseProduct'])) {
            $canUseProduct = $couponPrepareData['canUseProduct'];
        } else {
            $productList = (function ($type) {
                try {
                    $shopBindListConfig = [];
                    switch ($type) {
                        case CouponExtEnum::EXT_PLATFORM_DOUYIN:
                            $shopBindListConfig = ConfigModel::getConfigByTypeKey('posProduct', 'productBindDouyin');
                            break;
                        case CouponExtEnum::EXT_PLATFORM_MEITUAN:
                            $shopBindListConfig = ConfigModel::getConfigByTypeKey('posProduct', 'productBindMt');
                            break;
                        default:
                            break;
                    }

                    if (empty($shopBindListConfig)) {
                        return [];
                    }

                    $list = $shopBindListConfig[0]['value'] ?? [];

                    return json_decode($list, true);
                } catch (Exception $e) {
                    return [];
                }

            })($type);

            if (empty($productList)) {
                return '';
            }

            $productList = array_column($productList, null, 'skuId');

            $canUseProduct = $productList[$skuId]['canUseProduct'] ?? '';

            if (!is_numeric($canUseProduct)) {
                return $canUseProduct;
            }

            if (empty($canUseProduct)) {
                $title   = '【' . (CouponExtEnum::EXT_PLATFORM_TEXT[$type] ?? '') . '】关联商品缺失';
                $content = "门店ID:{$shopId} POS找不到关联商品 {$couponPrepareData['couponTitle']}({$skuId})，请联系 @胡迪 添加关联商品";
                BuildFs::newRobot($robotConfig)
                       ->setTitleContent($title, $content)
                       ->setAtUid('2c54915f')
                       ->send();

                return '';
            }
        }

        // 获取门店当前菜单
        $orderProductDetail = ProductShopService::getProductListInstance($shopId);
        $orderProductDetail = array_column($orderProductDetail, null, 'id');

        if (empty($orderProductDetail[$canUseProduct])) {
            $title   = '【' . (CouponExtEnum::EXT_PLATFORM_TEXT[$type] ?? '') . '】关联商品缺失';
            $content = "门店ID:{$shopId} 找不到关联商品 {$couponPrepareData['couponTitle']}({$skuId})，请联系 @胡迪 添加关联商品, 关联夸父 ID:" . $canUseProduct;

            BuildFs::newRobot($robotConfig)
                   ->setTitleContent($title, $content)
                   ->setAtUid('2c54915f')
                   ->send();

            return '';
        }
//
//        // 单菜处理
//
//        // 校验商品的价格是否一致
//        if ($orderProductDetail[$canUseProduct]['price'] != $couponPrepareData['deduction']) {
//            $title   = '【' . (CouponExtEnum::EXT_PLATFORM_TEXT[$type] ?? '') . '】关联商品缺失';
//            $content = "门店ID:{$shopId}  {$couponPrepareData['couponTitle']}({$skuId}) " . (CouponExtEnum::EXT_PLATFORM_TEXT[$type] ?? '') . "价格 {$couponPrepareData['deduction']} 与 POS 价格 {$orderProductDetail[$canUseProduct]['price']} 不符，联系 @胡迪 添加修改商品，商品 ID:" . $canUseProduct;
//            BuildFs::newRobot($robotConfig)
//                   ->setTitleContent($title, $content)
//                   ->setAtUid('2c54915f')
//                   ->send();
//
//            return '';
//        }

        return (string)$canUseProduct;
    }

    public static function getCanUseProductBySkuId2()
    {

    }

    public static function getRobotByType(int $type): string
    {
        $robotConfig = SendFs::ROBOT_POS_MISS_EXT_PRODUCT;
        switch ($type) {
            case CouponExtEnum::EXT_PLATFORM_DOUYIN:
                $robotConfig = SendFs::ROBOT_POS_MISS_EXT_PRODUCT;
                break;
            case CouponExtEnum::EXT_PLATFORM_MEITUAN:
                $robotConfig = SendFs::ROBOT_POS_MISS_MT_EXT_PRODUCT;
                break;
            default:
                break;
        }

        return $robotConfig;
    }


    /**
     * 统一格式化返回优惠券详情数据格式
     *
     * @param int $maxConsumeCount 关联张数，最大可验证张数
     * @param int $minConsumeCount 最小消费张数
     * @param string $couponSid 券的关联id
     * @param string $couponTitle 券名称
     * @param string $couponCode 券码
     * @param int $couponType 券类型
     * @param int $userPayMoney 购券实付金额(分)
     * @param int $deduction 券原价(分)
     * @param int $couponBeginTime 券使用开始时间(时间戳)
     * @param int $couponEndTime 券使用截止时间(时间戳)
     * @param int $couponFrom
     * @param array $dealMenu 菜单列表
     * @param string $canUseProduct kf 系统关联 id
     * @param string $skuId 三方券的 sku
     * @param array $canUseProducts kf 系统菜品信息多份
     * @return array
     */
    public static function formatPrepareResponseData(
        int $maxConsumeCount,
        int $minConsumeCount,
        string $couponSid,
        string $couponTitle,
        string $couponCode,
        int $couponType,
        int $userPayMoney,
        int $deduction,
        int $couponBeginTime,
        int $couponEndTime,
        int $couponFrom,
        array $dealMenu = [],
        string $canUseProduct = '',
        string $skuId = '',
        ?array $canUseProducts = null
    ): array {
        return [
            // 关联张数，最大可验证张数
            'count'           => $maxConsumeCount,
            // 最小消费张数
            'minConsume'      => $minConsumeCount,
            // 券的关联id
            'couponSid'       => $couponSid,
            // 券名称
            'couponTitle'     => $couponTitle,
            // 券码
            'couponCode'      => $couponCode,
            // 券类型 代金券等信息
            'couponType'      => $couponType,
            // 购券实付金额(分)
            'userPay'         => $userPayMoney,
            // 券原价(分)
            'deduction'       => $deduction,
            // 券使用开始时间(时间戳)
            'couponBeginTime' => $couponBeginTime,
            // 券使用截止时间(时间戳)
            'couponEndTime'   => $couponEndTime,
            // 券来源
            'couponFrom'      => $couponFrom,
            // 菜单列表
            'dealMenu'        => $dealMenu,
            // kf 系统关联 id,单个
            'canUseProduct'   => $canUseProduct,
            // kf 系统关联的 id 多个
            'canUseProducts'  => $canUseProducts,
            // 三方券的 sku id
            'skuId'           => $skuId,
        ];
    }


    /**
     * 统一格式化返回优惠券核销数据格式
     *
     * @param array $couponCodes
     * @param int $couponSid
     * @param string $couponTitle
     * @param int $deduction
     * @return array
     */
    public static function formatConsumeResponseData(
        array $couponCodes,
        int $couponSid,
        string $couponTitle,
        int $deduction
    ): array {
        return [
            'couponCodes' => $couponCodes,
            'couponSid'   => $couponSid,
            'couponTitle' => $couponTitle,
            'deduction'   => $deduction, // TODO 代金券，需要实际测试
        ];
    }


    /**
     * 券内多个套餐详情
     * @param int $type
     * @param array $couponPrepareData
     * @param int $shopId
     * @return array
     * @throws Exception
     */
    public static function getCanUseProductsBySkuId(
        int $type,
        array $couponPrepareData,
        int $shopId
    ): array {

        $returnData    = [
            'isRepeat'    => false, // 是否可以重复
            'selectLimit' => 1, // n 选 1,
            'list'        => [] // 关联的菜品数据
            // [
            //"canUseProduct": 1,
            //"productLimit": 1
            //]
        ];
        $canUseProduct = $couponPrepareData['canUseProduct'];
        $skuId         = $couponPrepareData['skuId'] ?? '';

        // 判断是否是单品
        if (is_numeric($canUseProduct)) {
            $returnData['list'][] = [
                'canUseProduct' => $canUseProduct,
                'productLimit'  => 1
            ];

            return $returnData;
        }

        // 判断是多选还是多份
        $explodeList = array_filter(explode('|', $canUseProduct));

        // 规则不满足
        if (count($explodeList) < 1) {
            return $returnData;
        }

        $productList = explode(',', $explodeList[0]);

        // 规则不满足
        if (!count($productList)) {
            return $returnData;
        }
        $selectLimit = $explodeList[1] ?? 1;

        if (empty($explodeList[2])) {
            $isRepeat = false;
        } else {
            $isRepeat = (bool)$explodeList[2] ?? false;
        }

        $returnData['isRepeat']    = $isRepeat;
        $returnData['selectLimit'] = $selectLimit;

        $robotConfig = self::getRobotByType($type);

        // 获取门店当前菜单
        $orderProductDetail = ProductShopService::getProductListInstance($shopId);
        $orderProductDetail = array_column($orderProductDetail, null, 'id');

        foreach ($productList as $product) {
            $tempProduct = explode('-', $product);

            $canUseProduct = $tempProduct[0];// 对应菜单id
            $productLimit  = $tempProduct[1];// 当前菜可选次数

            if (empty($orderProductDetail[$canUseProduct])) {
                $title   = '【' . (CouponExtEnum::EXT_PLATFORM_TEXT[$type] ?? '') . '】关联商品缺失';
                $content = "门店ID:{$shopId} 找不到关联商品 {$couponPrepareData['couponTitle']}({$skuId})，请联系 @胡迪 添加关联商品, 关联夸父 ID:" . $canUseProduct;

                BuildFs::newRobot($robotConfig)
                       ->setTitleContent($title, $content)
                       ->setAtUid('2c54915f')
                       ->send();
                continue;
            }

            $returnData['list'][] = [
                'canUseProduct' => $canUseProduct,// 菜品id
                'productLimit'  => $productLimit,// 一个套餐份数
            ];
        }
        return $returnData;
    }
}
